<script setup>
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import GoodsItem from '@/components/GoodsItem.vue'
import { getGoodsList } from '@/api/goods'

const route = useRoute()

const m = ref(0)
const n = ref(0)
const list = ref([])

const getGoods = async (obj) => {
  const { sortType, sortPrice } = obj
  const goodsName = route.query.keyword
  const categoryId = route.query.categoryId
  const { data } = await getGoodsList({
    goodsName,
    sortType,
    categoryId,
    sortPrice
  })
  list.value = data.list.data
}

const sortByAll = () => {
  n.value = 0
  m.value = 0
  getGoods({ sortType: 'all', sortPrice: null })
}

const sortBySale = () => {
  n.value = 1
  m.value = 0
  getGoods({ sortType: 'sales', sortPrice: null })
}

const sortByPrice = () => {
  n.value = 2
  m.value = m.value < 2 ? m.value + 1 : 1
  getGoods({ sortType: 'price', sortPrice: m.value - 1 })
}

const init = () => {
  getGoods({ sortType: 'all', sortPrice: null })
}
init()
</script>

<template>
  <div class="list">
    <van-nav-bar
      title="商品列表"
      left-arrow
      fixed
      @click-left="$router.back()"
    />
    <van-search
      readonly
      shape="round"
      placeholder="搜索商品"
      @click="$router.push('/search')"
    />

    <div class="sort">
      <span class="sort-item" @click="sortByAll" :class="{ selected: n === 0 }"
        >综合</span
      >
      <span class="sort-item" @click="sortBySale" :class="{ selected: n === 1 }"
        >销量</span
      >

      <span class="sort-item" @click="sortByPrice">
        <span :class="{ selected: n === 2 }">价格</span>
        <div class="arrow">
          <van-icon
            name="arrow-up"
            size="12px"
            :class="{ selected: m === 1 }"
          />
          <van-icon
            name="arrow-down"
            size="12px"
            :class="{ selected: m === 2 }"
          />
        </div>
      </span>
    </div>

    <div class="items">
      <GoodsItem
        :item="item"
        v-for="item in list"
        :key="item.goods_id"
      ></GoodsItem>
    </div>
  </div>
</template>

<style lang="less" scoped>
.list {
  padding-top: 46px;
  background-color: white;
}

.van-nav-bar {
  ::v-deep .van-nav-bar__title {
    font-weight: bold;
  }

  ::v-deep .van-icon-arrow-left {
    color: black;
  }
}

.sort {
  width: 375px;
  height: 25px;
  padding: 10px 0;
  display: flex;
  justify-content: space-between;
  line-height: 25px;

  .sort-item {
    width: 125px;
    height: 25px;
    text-align: center;
    font-size: 14px;
    color: #000;
  }

  .sort-item:last-child {
    position: relative;

    span {
      position: absolute;
      left: 40px;
    }

    .arrow {
      width: 12px;
      height: 22px;
      position: absolute;
      left: 75px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    }
  }

  .selected {
    color: #e49a3d !important;
  }
}
</style>
